//
//  XTXNetworkingPageViewController.m
//  cpcpcp
//
//  Created by XYC on 2019/6/20.
//  Copyright © 2019 XYC. All rights reserved.
//

#import "XTXNetworkingPageViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>

@interface XTXNetworkingPageViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, assign) BOOL iswangcheng;
@property (nonatomic, strong) NSString *dingdanStr;

@end

@implementation XTXNetworkingPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wangchengMM:) name:@"wangchengMM" object:nil];
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, zhuangtaiGao, pingmuKuan, pingmuGao-zhuangtaiGao)];
    webView.delegate = self;
    [self.view addSubview:webView];
    
    if (@available(iOS 11.0, *)) {
        webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.dizhiStr]];
    [webView loadRequest:request];
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    if ([self.dizhiStr isEqualToString:xieyiUrl]) {
        self.title = @"用户协议";
        webView.frame = CGRectMake(0, zhuangtaiDaohangGao, pingmuKuan, pingmuGao);
    }
    else {
        if (liuhaiping) {
            webView.frame = CGRectMake(0, zhuangtaiGao, pingmuKuan, pingmuGao-zhuangtaiGao-20);
        }
    }
    
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.view.backgroundColor = [UIColor whiteColor];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wangchengMM" object:nil];
}

-(void)wangchengMM:(NSNotification *)notification
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    WeakSelf
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //定义好JS要调用的方法，finish就是调用的方法名
    context[@"ButtonListener"] = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        });
    };
    [self.hud hideAnimated:YES];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    NSString* reqUrl = request.URL.absoluteString;
    if ([reqUrl hasPrefix:@"a"] ) {
        BOOL bSucc = [[UIApplication sharedApplication] openURL:request.URL];
        NSLog(@"bSucc == %d", bSucc);
        return NO;
    }
    NSLog(@"字符串  --- %@" ,reqUrl);
    NSString *orderNo = [NSString stringWithFormat:@"%@/resultApp?orderno=", Portaddress];
    if ([reqUrl hasPrefix:orderNo]) {
        self.iswangcheng = YES;
        self.dingdanStr = [self getURLParameters:reqUrl][@"orderno"];
    }
    NSString *tokenError = [NSString stringWithFormat:@"%@/tokenError", Portaddress];
    if ([reqUrl hasPrefix:tokenError]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [XTXGongView denglujiemiandezhanshiEventClick];
        });
    }
    return YES;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  截取URL中的参数
 *
 *  @return NSMutableDictionary parameters
 */
- (NSMutableDictionary *)getURLParameters:(NSString *)urlStr {
    
    // 查找参数
    NSRange range = [urlStr rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    // 以字典形式将参数返回
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSString *parametersString = [urlStr substringFromIndex:range.location + 1];
    
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}

@end
